/**
 * amis v6.13.0
 * build time: 2025-08-12
 * Copyright 2018-2025 baidu
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _Spinner = require('amis-ui/lib/components/Spinner');
var _Icon = require('amis-ui/lib/components/Icon');
var _TooltipWrapper = require('amis-ui/lib/components/TooltipWrapper');
var _Checkbox = require('amis-ui/lib/components/Checkbox');
var tslib = require('tslib');
var React = require('react');
var inRange = require('lodash/inRange');
var amisCore = require('amis-core');
var StaticHoc = require('./StaticHoc.js');
var debounce = require('lodash/debounce');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _Spinner__default = /*#__PURE__*/_interopDefaultLegacy(_Spinner);
var _Icon__default = /*#__PURE__*/_interopDefaultLegacy(_Icon);
var _TooltipWrapper__default = /*#__PURE__*/_interopDefaultLegacy(_TooltipWrapper);
var _Checkbox__default = /*#__PURE__*/_interopDefaultLegacy(_Checkbox);
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var inRange__default = /*#__PURE__*/_interopDefaultLegacy(inRange);
var debounce__default = /*#__PURE__*/_interopDefaultLegacy(debounce);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
var _J$F_ = (__react_jsx__["default"] || __react_jsx__).Fragment;


;var CheckboxesControl = /** @class */function (_super) {
  tslib.__extends(CheckboxesControl, _super);
  function CheckboxesControl() {
    var _this = _super !== null && _super.apply(this, arguments) || this;
    _this.checkboxRef = React__default["default"].createRef();
    _this.childRefs = [];
    return _this;
  }
  CheckboxesControl.prototype.doAction = function (action, data, throwErrors) {
    var _a, _b;
    var _c = this.props,
      resetValue = _c.resetValue,
      onChange = _c.onChange,
      formStore = _c.formStore,
      store = _c.store,
      name = _c.name;
    var actionType = action === null || action === void 0 ? void 0 : action.actionType;
    if (actionType === 'clear') {
      onChange('');
    } else if (actionType === 'reset') {
      var pristineVal = (_b = amisCore.getVariable((_a = formStore === null || formStore === void 0 ? void 0 : formStore.pristine) !== null && _a !== void 0 ? _a : store === null || store === void 0 ? void 0 : store.pristine, name)) !== null && _b !== void 0 ? _b : resetValue;
      onChange(pristineVal !== null && pristineVal !== void 0 ? pristineVal : '');
    }
  };
  CheckboxesControl.prototype.reload = function (subpath, query) {
    var reload = this.props.reloadOptions;
    reload && reload(subpath, query);
  };
  CheckboxesControl.prototype.handleAddClick = function () {
    var onAdd = this.props.onAdd;
    onAdd && onAdd();
  };
  CheckboxesControl.prototype.handleEditClick = function (e, item) {
    var onEdit = this.props.onEdit;
    e.preventDefault();
    e.stopPropagation();
    onEdit && onEdit(item);
  };
  CheckboxesControl.prototype.handleDeleteClick = function (e, item) {
    var onDelete = this.props.onDelete;
    e.preventDefault();
    e.stopPropagation();
    onDelete && onDelete(item);
  };
  CheckboxesControl.prototype.componentDidMount = function () {
    this.updateBorderStyle();
    var updateBorderStyleFn = debounce__default["default"](this.updateBorderStyle, 100);
    if (this.checkboxRef.current) {
      // 监听容器宽度变化，更新边框样式
      this.checkboxRefObserver = new ResizeObserver(updateBorderStyleFn);
      this.checkboxRefObserver.observe(this.checkboxRef.current);
    }
  };
  CheckboxesControl.prototype.componentWillUnmount = function () {
    var _a;
    (_a = this.checkboxRefObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
  };
  CheckboxesControl.prototype.updateBorderStyle = function () {
    if (this.props.optionType !== 'button') {
      return;
    }
    if (!this.childRefs.length) {
      return;
    }
    var children = this.childRefs.map(function (item) {
      return item === null || item === void 0 ? void 0 : item.ref;
    });
    var lastOffsetTop = children[0].labelRef.current.offsetTop;
    var options = [];
    var len = children.length;
    options[0] = 'first';
    var lastLineStart = 0;
    for (var i = 1; i < len; i++) {
      var item = children[i];
      // 如果当前元素的 offsetTop 与上一个元素的 offsetTop 不同，则说明是新的一行
      var currentOffsetTop = item.labelRef.current.offsetTop;
      options[i] = '';
      if (currentOffsetTop !== lastOffsetTop) {
        options[i] = 'first';
        options[i - 1] += ' last';
        lastLineStart = i;
        lastOffsetTop = currentOffsetTop;
      }
    }
    options[len - 1] += ' last';
    options.forEach(function (option, index) {
      if (index >= lastLineStart) {
        option += ' last-line';
      }
      children[index].setClassName(option);
    });
  };
  CheckboxesControl.prototype.renderGroup = function (option, index) {
    var _this = this;
    var _a;
    var _b = this.props,
      cx = _b.classnames,
      labelField = _b.labelField;
    if (!((_a = option.children) === null || _a === void 0 ? void 0 : _a.length)) {
      return null;
    }
    var children = option.children.map(function (option, index) {
      return _this.renderItem(option, index);
    });
    var body = this.columnsSplit(children);
    return _J$X_("div", {
      key: 'group-' + index,
      className: cx('CheckboxesControl-group', option.className)
    }, _J$X_("label", {
      className: cx('CheckboxesControl-groupLabel', option.labelClassName)
    }, option[labelField || 'label']), body);
  };
  CheckboxesControl.prototype.addChildRefs = function (el) {
    el && this.childRefs.push(el);
  };
  CheckboxesControl.prototype.renderItem = function (option, index) {
    var _this = this;
    var _a;
    if ((_a = option.children) === null || _a === void 0 ? void 0 : _a.length) {
      return this.renderGroup(option, index);
    }
    var _b = this.props,
      render = _b.render,
      itemClassName = _b.itemClassName,
      onToggle = _b.onToggle,
      selectedOptions = _b.selectedOptions,
      disabled = _b.disabled,
      inline = _b.inline,
      labelClassName = _b.labelClassName,
      labelField = _b.labelField,
      removable = _b.removable,
      editable = _b.editable,
      __ = _b.translate,
      optionType = _b.optionType,
      menuTpl = _b.menuTpl,
      data = _b.data,
      cx = _b.classnames,
      testIdBuilder = _b.testIdBuilder;
    var labelText = String(option[labelField || 'label']);
    var optionLabelClassName = option['labelClassName'];
    var itemTestIdBuilder = testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('item-' + labelText || index);
    var finalDisabled = disabled || option.disabled;
    return _J$X_(_Checkbox__default["default"], {
      className: itemClassName,
      key: index,
      onChange: function () {
        return onToggle(option);
      },
      checked: !!~selectedOptions.indexOf(option),
      disabled: finalDisabled,
      inline: inline,
      labelClassName: optionLabelClassName || labelClassName,
      description: option.description,
      optionType: optionType,
      testIdBuilder: itemTestIdBuilder,
      ref: this.addChildRefs
    }, menuTpl ? render("checkboxes/".concat(index), menuTpl, {
      data: amisCore.createObject(data, option)
    }) : labelText, option.disabledTip && finalDisabled ? _J$X_(_TooltipWrapper__default["default"], {
      placement: "right",
      tooltip: option.disabledTip,
      trigger: "hover"
    }, _J$X_("a", {
      className: cx('Select-option-disabledTip')
    }, _J$X_(_Icon__default["default"], {
      className: "icon",
      icon: "question2"
    }))) : null, removable && amisCore.hasAbility(option, 'removable') ? _J$X_("a", {
      "data-tooltip": __('Select.clear'),
      "data-position": "left"
    }, _J$X_(_Icon__default["default"], {
      icon: "minus",
      className: "icon",
      onClick: function (e) {
        return _this.handleDeleteClick(e, option);
      }
    })) : null, editable && amisCore.hasAbility(option, 'editable') ? _J$X_("a", {
      "data-tooltip": "\u7F16\u8F91",
      "data-position": "left"
    }, _J$X_(_Icon__default["default"], {
      icon: "pencil",
      className: "icon",
      onClick: function (e) {
        return _this.handleEditClick(e, option);
      }
    })) : null);
  };
  CheckboxesControl.prototype.columnsSplit = function (body) {
    var _a = this.props,
      columnsCount = _a.columnsCount,
      cx = _a.classnames;
    var result = [];
    var tmp = [];
    body.forEach(function (node) {
      // 如果有分组，组内单独分列
      if (node && node.key && String(node.key).startsWith('group')) {
        // 夹杂在分组间的无分组选项，分别成块
        if (tmp.length) {
          result.push(amisCore.columnsSplit(tmp, cx, columnsCount));
          tmp = [];
        }
        result.push(node);
      } else {
        tmp.push(node);
      }
    });
    // 收尾
    tmp.length && result.push(amisCore.columnsSplit(tmp, cx, columnsCount));
    return result;
  };
  CheckboxesControl.prototype.render = function () {
    var _this = this;
    var _a = this.props,
      className = _a.className,
      style = _a.style,
      disabled = _a.disabled,
      placeholder = _a.placeholder,
      options = _a.options,
      inline = _a.inline,
      columnsCount = _a.columnsCount,
      selectedOptions = _a.selectedOptions,
      onToggle = _a.onToggle,
      onToggleAll = _a.onToggleAll,
      checkAll = _a.checkAll,
      checkAllText = _a.checkAllText,
      cx = _a.classnames,
      itemClassName = _a.itemClassName,
      labelClassName = _a.labelClassName,
      creatable = _a.creatable,
      addApi = _a.addApi,
      createBtnLabel = _a.createBtnLabel,
      __ = _a.translate,
      optionType = _a.optionType,
      loading = _a.loading,
      loadingConfig = _a.loadingConfig,
      themeCss = _a.themeCss,
      id = _a.id,
      env = _a.env,
      ns = _a.classPrefix;
    var body = [];
    if (options && options.length) {
      body = options.map(function (option, key) {
        return _this.renderItem(option, key);
      });
    }
    if (checkAll && body.length && optionType === 'default') {
      body.unshift(_J$X_(_Checkbox__default["default"], {
        key: "checkall",
        className: itemClassName,
        onChange: onToggleAll,
        checked: !!selectedOptions.length,
        partial: inRange__default["default"](selectedOptions.length, 0, amisCore.flattenTreeWithLeafNodes(options).length),
        disabled: disabled,
        inline: inline,
        labelClassName: labelClassName
      }, checkAllText !== null && checkAllText !== void 0 ? checkAllText : __('Checkboxes.selectAll')));
    }
    body = this.columnsSplit(body);
    var css = amisCore.formateCheckThemeCss(themeCss, 'checkboxes');
    return _J$X_("div", {
      className: cx("CheckboxesControl", className, amisCore.setThemeClassName(tslib.__assign(tslib.__assign({}, this.props), {
        name: ['checkboxesControlClassName', 'checkboxesControlCheckedClassName', 'checkboxesClassName', 'checkboxesCheckedClassName', 'checkboxesInnerClassName', 'checkboxesShowClassName'],
        id: id,
        themeCss: css
      }))),
      ref: this.checkboxRef
    }, body && body.length ? body : loading ? null : _J$X_("span", {
      className: "Form-placeholder"
    }, __(placeholder)), loading ? _J$X_(_Spinner__default["default"], {
      show: true,
      icon: "reload",
      size: "sm",
      spinnerClassName: cx('Checkboxes-spinner'),
      loadingConfig: loadingConfig
    }) : null, (creatable || addApi) && !disabled ? _J$X_("a", {
      className: cx('Checkboxes-addBtn'),
      onClick: this.handleAddClick
    }, _J$X_(_Icon__default["default"], {
      icon: "plus",
      className: "icon"
    }), __(createBtnLabel)) : null, _J$X_(amisCore.CustomStyle, tslib.__assign({}, this.props, {
      config: {
        themeCss: css,
        classNames: [{
          key: 'checkboxesControlClassName',
          weights: {
            default: {
              inner: ".".concat(ns, "Checkbox:not(.checked):not(.disabled)")
            },
            hover: {
              suf: " .".concat(ns, "Checkbox:not(.disabled):not(.checked)")
            },
            disabled: {
              inner: ".".concat(ns, "Checkbox.disabled:not(.checked)")
            }
          }
        }, {
          key: 'checkboxesControlCheckedClassName',
          weights: {
            default: {
              inner: ".".concat(ns, "Checkbox.checked:not(.disabled)")
            },
            hover: {
              suf: " .".concat(ns, "Checkbox.checked:not(.disabled)")
            },
            disabled: {
              inner: ".".concat(ns, "Checkbox.checked.disabled")
            }
          }
        }, {
          key: 'checkboxesClassName',
          weights: {
            default: {
              inner: ".".concat(ns, "Checkbox:not(.checked):not(.disabled) > i")
            },
            hover: {
              suf: " .".concat(ns, "Checkbox:not(.disabled):not(.checked)"),
              inner: '> i'
            },
            disabled: {
              inner: ".".concat(ns, "Checkbox.disabled:not(.checked) > i")
            }
          }
        }, {
          key: 'checkboxesCheckedClassName',
          weights: {
            default: {
              inner: ".".concat(ns, "Checkbox:not(.disabled) > i")
            },
            hover: {
              suf: " .".concat(ns, "Checkbox:not(.disabled)"),
              inner: '> i'
            },
            disabled: {
              inner: ".".concat(ns, "Checkbox.disabled > i")
            }
          }
        }, {
          key: 'checkboxesInnerClassName',
          weights: {
            default: {
              inner: ".".concat(ns, "Checkbox:not(.disabled) > i .icon")
            },
            hover: {
              suf: " .".concat(ns, "Checkbox:not(.disabled)"),
              inner: '> i .icon'
            },
            disabled: {
              inner: ".".concat(ns, "Checkbox.disabled > i .icon")
            }
          }
        }, {
          key: 'checkboxesShowClassName',
          weights: {
            default: {
              inner: ".".concat(ns, "Checkbox > i")
            }
          }
        }],
        id: id
      },
      env: env
    })));
  };
  CheckboxesControl.defaultProps = {
    columnsCount: 1,
    multiple: true,
    placeholder: 'placeholder.noOption',
    creatable: false,
    inline: true,
    createBtnLabel: 'Select.createLabel',
    optionType: 'default'
  };
  tslib.__decorate([amisCore.autobind, tslib.__metadata("design:type", Function), tslib.__metadata("design:paramtypes", []), tslib.__metadata("design:returntype", void 0)], CheckboxesControl.prototype, "handleAddClick", null);
  tslib.__decorate([amisCore.autobind, tslib.__metadata("design:type", Function), tslib.__metadata("design:paramtypes", [Event, Object]), tslib.__metadata("design:returntype", void 0)], CheckboxesControl.prototype, "handleEditClick", null);
  tslib.__decorate([amisCore.autobind, tslib.__metadata("design:type", Function), tslib.__metadata("design:paramtypes", [Event, Object]), tslib.__metadata("design:returntype", void 0)], CheckboxesControl.prototype, "handleDeleteClick", null);
  tslib.__decorate([amisCore.autobind, tslib.__metadata("design:type", Function), tslib.__metadata("design:paramtypes", []), tslib.__metadata("design:returntype", void 0)], CheckboxesControl.prototype, "updateBorderStyle", null);
  tslib.__decorate([amisCore.autobind, tslib.__metadata("design:type", Function), tslib.__metadata("design:paramtypes", [Object]), tslib.__metadata("design:returntype", void 0)], CheckboxesControl.prototype, "addChildRefs", null);
  tslib.__decorate([StaticHoc.supportStatic(), tslib.__metadata("design:type", Function), tslib.__metadata("design:paramtypes", []), tslib.__metadata("design:returntype", void 0)], CheckboxesControl.prototype, "render", null);
  return CheckboxesControl;
}(React__default["default"].Component);
var CheckboxesControlRenderer = /** @class */function (_super) {
  tslib.__extends(CheckboxesControlRenderer, _super);
  function CheckboxesControlRenderer() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  CheckboxesControlRenderer = tslib.__decorate([amisCore.OptionsControl({
    type: 'checkboxes',
    sizeMutable: false,
    thin: true
  })], CheckboxesControlRenderer);
  return CheckboxesControlRenderer;
}(CheckboxesControl);

exports.CheckboxesControlRenderer = CheckboxesControlRenderer;
exports["default"] = CheckboxesControl;
